package com.tutor.lzm.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tutor.lzm.R;
import com.tutor.lzm.app.Constant;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.request.VersionCheckRequest;
import com.tutor.lzm.http.response.VersionCheckResponse;
import com.tutor.syslib.Logs;
import com.tutor.syslib.util.AndroidUtils;
import com.tutor.syslib.util.MessageTools;


public class UpdateManager {

    private String tag = "UpdateManager";
    private static UpdateManager updateManager;
    private String appVersion;

    private Context mContext;
    // 通知对话框
    private Dialog noticeDialog;
    // 下载对话框
    private Dialog downloadDialog;
    // '已经是最新' 或者 '无法获取最新版本' 的对话框
    private Dialog latestOrFailDialog;
    // 进度条
    private ProgressBar mProgress;
    // 显示下载数值
    private TextView mProgressText;
    // 查询动画
    private ProgressDialog mProDialog;
    // 进度值
    private int progress;
    // 下载线程
    private Thread downLoadThread;
    // 终止标记
    private boolean interceptFlag;
    // private EMConversation conversation;
    // 返回的安装包url
    private String apkUrl = "";
    // 下载文件大小
    private String apkFileSize;
    // 已下载文件大小
    private String tmpFileSize;

    private TextView mDetail;

    private boolean isShowNoUpdate = false;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {

            switch (msg.what) {
                case Constant.UPDATE_UI:
                    mProgress.setProgress(progress);
                    mProgressText.setText(tmpFileSize + "/" + apkFileSize);
                    break;
                case Constant.MSG_LOAD_OVER:
                    downloadDialog.dismiss();

                    break;
                case Constant.MSG_LOAD_ERROR:
                    downloadDialog.dismiss();
                    // UIHelper.ToastMessage(mContext, R.layout.toastmessage_text,
                    // "无法下载安装文件，请检查SD卡是否挂载", Toast.LENGTH_SHORT);
                    break;
            }
        }

        ;
    };


    public static UpdateManager getUpdateManager() {

        if (updateManager == null) {
            updateManager = new UpdateManager();
        }
        updateManager.interceptFlag = false;
        return updateManager;
    }


    /**
     * 检查App更新
     *
     * @param context
     * @param isShowMsg 是否显示提示消息
     */
    public void checkAppUpdate(final Context context, final boolean isShowMsg, final boolean isShowNoUpdate) {

        this.isShowNoUpdate = isShowNoUpdate;

        this.mContext = context;

        // conversation = EMChatManager.getInstance().getConversation( "10001"
        // );
        //
        // // 把message设为已读
        // EMMessage msg = conversation.getMessage( NewQSHealthApplication.userLoginInfo.getPushMessageId() );
        // if( msg != null ) {
        // msg.isAcked = true;
        // }
        // // 把此会话的未读数置为0
        // conversation.resetUnsetMsgCount();
        if (isShowMsg) {
            if (mProDialog == null)
                mProDialog = ProgressDialog.show(mContext, null, "正在检测，请稍后...", true, true);
            else if (mProDialog.isShowing() || (latestOrFailDialog != null && latestOrFailDialog.isShowing()))
                return;
        }

        String versionName = AndroidUtils.getCurrentVersionName(context);
        VersionCheckRequest request = new VersionCheckRequest();
        request.versionCode = versionName;

        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                VersionCheckResponse versionCheckResponse = (VersionCheckResponse) response;
                if (versionCheckResponse.status == 0) {
                    // 不需要跟新
                    MessageTools.showDialogOk(context, "当前已经是最新版本");
                    mProDialog.dismiss();
                } else if (versionCheckResponse.isForced.equals("1")) {
                    // 需要更新
                    if (versionCheckResponse.isForced.equals("0")) {
                        // 普通更新
                        showNoticeDialog(versionCheckResponse.updateUrl);
                    } else if (versionCheckResponse.isForced.equals("1")) {
                        // 强制更新
                        forcedUpdate(context, versionCheckResponse.updateUrl);
                    }
                }


            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                // 进度条对话框不显示 - 检测结果也不显示
                if (mProDialog != null && !mProDialog.isShowing()) {
                    return;
                }
                // 关闭并释放释放进度条对话框
                if (isShowMsg && mProDialog != null) {
                    mProDialog.dismiss();
                    mProDialog = null;
                }
            }
        });

    }


    public void forcedUpdate(Context ctx, String message, String url) {

        apkUrl = url;
        forcedUpdate(ctx, message);
    }


    /**
     * 强制更新
     */
    private void forcedUpdate(Context ctx, String message) {

        if (ctx == null) {
            return;
        }

        String temp = StringTools.charRepalce(message);
        Builder builder = new Builder(ctx).setMessage(temp).setPositiveButton("立即更新", new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

                showDownloadDialog();
                dialog.dismiss();

            }
        });
        builder.setTitle("新版本介绍");
        AlertDialog dialog = builder.create();
        dialog.show();

    }

    /**
     * 显示版本更新通知对话框
     */
    private void showNoticeDialog(String message) {

        String temp = StringTools.charRepalce(message);
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View longinDialogView = layoutInflater.inflate(R.layout.updatedialog, null);

        // 获取布局中的控件
        mDetail = (TextView) longinDialogView.findViewById(R.id.app_detail);
        mDetail.setText(temp);
        Builder builder = new Builder(mContext);
        builder.setView(longinDialogView);
        builder.setTitle("康信更新");
        builder.setPositiveButton("下次再说", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        });
        builder.setNegativeButton("立即更新", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                showDownloadDialog();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }


    /**
     * 显示下载对话框
     */
    @SuppressLint("InflateParams")
    private void showDownloadDialog() {

        Builder builder = new Builder(mContext);
        builder.setTitle("正在下载新版本");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_dialog, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        mProgressText = (TextView) v.findViewById(R.id.update_progress_text);

        builder.setView(v);
        builder.setNegativeButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                interceptFlag = true;
            }
        });
        builder.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {

                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.show();

        downloadApk();
    }


    /**
     * apk下载
     *
     * @param context
     * @param urlString void
     * @throws
     * @since 1.0.0
     */
    private void dowanLoadFile(Context context, String urlString) {

        try {

            String path = Environment.getExternalStorageDirectory() + "/download/";
            String[] name = urlString.split("/");
            path = path + name[name.length - 1];

            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(3 * 60 * 1000);
            connection.setReadTimeout(3 * 60 * 1000);
            // 实现连接
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream inputStream = connection.getInputStream();

                FileOutputStream fos = new FileOutputStream(file);
                int length = connection.getContentLength();

                DecimalFormat df = new DecimalFormat("0.00");
                apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = inputStream.read(buf);
                    count += numread;
                    // 进度条下面显示的当前下载文件大小
                    tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
                    // 当前进度值
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    mHandler.sendEmptyMessage(Constant.UPDATE_UI);
                    if (numread <= 0) {
                        // 下载完成 - 将临时下载文件转成APK文件
                        // 通知安装
                        mHandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
                        AndroidUtils.inStallApk(mContext, file);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载

                fos.close();
                inputStream.close();
            } else {
                MessageTools.showDialogOk(context, "请求失败");
            }
        } catch (Exception e) {
            mHandler.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
            Logs.e(tag, e.getMessage());
        }
    }


    /**
     * apk下载线程
     *
     * @since 1.0.0
     */
    private Runnable downRunnable = new Runnable() {

        @Override
        public void run() {

            dowanLoadFile(mContext, apkUrl);
        }
    };


    /**
     * 下载apk线程
     */
    private void downloadApk() {

        // downLoadThread = new Thread( mdownApkRunnable );
        downLoadThread = new Thread(downRunnable);
        downLoadThread.start();
    }

}
